<template>
  <a-drawer
    :title="title"
    placement="right"
    :closable="false"
    :visible="visible"
    @close="onClose"
    :destroyOnClose="true"
    :width="900"
    :headerStyle="{ position: 'fixed', top: 0, width: '100%', background: '#fff', zIndex: 2 }"
    :body-style="{ paddingBottom: '80px' }"
  >
    <a-form @submit="handleSubmit" :form="form" :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }" style="padding-top: 60px">
      <a-form-item label="优惠券名称">
        <a-input v-decorator="['innerName', { rules: [{ required: true, message: '请输入优惠券名称！' }] }]" name="name" placeholder="请输入" autocomplete="off" />
      </a-form-item>
      <a-form-item label="外部名称">
        <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入外部名称！' }] }]" name="name" placeholder="请输入" autocomplete="off" />
      </a-form-item>
      <a-divider style="margin-top: 0" />
      <a-form-item label="券类型">
        <a-select
          v-decorator="['type', { rules: [{ required: true, message: '请选择！' }] }]"
          placeholder="请选择"
          @change="e => handleSelectChange(e, 'type')"
          :getPopupContainer="triggerNode => triggerNode.parentNode"
        >
          <a-select-option :value="0">现金券</a-select-option>
          <a-select-option :value="1">折扣券</a-select-option>
        </a-select>
      </a-form-item>
      <template v-if="toggle.type == 0">
        <a-form-item label="面额">
          <a-input v-decorator="['amount', { rules: [{ required: true, message: '请输入面额！' }] }]" name="name" placeholder="请输入" autocomplete="off" />
        </a-form-item>
        <a-form-item label="实付最低折扣">
          <a-input v-decorator="['payDiscount', { rules: [{ required: true, message: '请输入！' }] }]" name="name" placeholder="请输入" autocomplete="off" />
        </a-form-item>
        <a-form-item label="使用门槛">
          <a-input v-decorator="['useLimit', { rules: [{ required: true, message: '请输入！' }] }]" name="name" placeholder="请输入" autocomplete="off" />
        </a-form-item>
        <a-form-item label="同类型叠加使用">
          <a-radio-group name="radioGroup" v-decorator="['sameTypeAdd', { rules: [{ required: true, message: '请选择！' }] }]">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </template>
      <template v-if="toggle.type == 1">
        <a-form-item label="折扣">
          <a-input v-decorator="['discount', { rules: [{ required: true, message: '请输入折扣！' }] }]" name="name" placeholder="请输入" autocomplete="off" style="width: 73%; margin-right: 8px" />
          例如36折：0.36
        </a-form-item>
        <a-form-item label="最高商品数量">
          <a-input v-decorator="['exchangeQuantity', { rules: [{ required: true, message: '请输入！' }] }]" name="name" placeholder="请输入" autocomplete="off" />
        </a-form-item>
      </template>
      <a-divider style="margin-top: 0" />
      <a-form-item label="是否折上折">
        <a-radio-group name="radioGroup" v-decorator="['overly', { rules: [{ required: true, message: '请选择！' }] }]">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="0">否</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="有效期类型">
        <a-select
          v-decorator="['expireType', { rules: [{ required: true, message: '请选择！' }] }]"
          placeholder="请选择"
          @change="e => handleSelectChange(e, 'expireType')"
          :getPopupContainer="triggerNode => triggerNode.parentNode"
        >
          <a-select-option :value="0">指定时间</a-select-option>
          <a-select-option :value="1">按领取时间顺延</a-select-option>
        </a-select>
      </a-form-item>
      <template v-if="toggle.expireType == 0">
        <a-form-item label="开始日期">
          <a-date-picker v-decorator="['startDate', { rules: [{ required: true, message: '请选择！' }] }]" />
        </a-form-item>
        <a-form-item label="结束日期">
          <a-date-picker v-decorator="['endDate', { rules: [{ required: true, message: '请选择！' }] }]" />
        </a-form-item>
      </template>
      <template v-if="toggle.expireType == 1">
        <a-form-item label="领取后">
          <a-input v-decorator="['endDays', { rules: [{ required: true, message: '请输入！' }] }]" name="name" placeholder="请输入" autocomplete="off" style="width: 85%" /> 天内有效
        </a-form-item>
      </template>
      <a-form-item label="使用场景">
        <a-checkbox-group name="checkboxGroup" v-decorator="['useTypeList', { rules: [{ required: true, message: '请选择！' }] }]" :disabled="editId != 'add'">
          <a-checkbox value="1">BOX</a-checkbox>
          <a-checkbox value="5">微商城</a-checkbox>
          <a-checkbox value="6">线下</a-checkbox>
        </a-checkbox-group>
      </a-form-item>
      <a-divider />
      <a-form-item label="商品">
        <a-select v-decorator="['goodFtiler', { initialValue: 3 }]" placeholder="请选择" @change="e => handleSelectChange(e, 'goodFilter')" :getPopupContainer="triggerNode => triggerNode.parentNode">
          <a-select-option :value="1">可用</a-select-option>
          <a-select-option :value="2">不可用</a-select-option>
          <a-select-option :value="3">无</a-select-option>
        </a-select>
      </a-form-item>
      <template v-if="toggle.goods">
        <a-form-item label="限定商品">
          <a-select
            v-decorator="['goodsFilter', { initialValue: 0 }]"
            placeholder="请选择"
            @change="e => handleSelectChange(e, 'goodsFilter')"
            :getPopupContainer="triggerNode => triggerNode.parentNode"
          >
            <a-select-option :value="0">全部</a-select-option>
            <a-select-option :value="1">限定单品</a-select-option>
          </a-select>
          <template v-if="toggle.goodsFilter == 1">
            <a-button type="primary" style="margin-right: 8px; margin-top: 12px" @click="handleImportXls">导入商品</a-button>
            <a-button>导出商品</a-button>
          </template>
        </a-form-item>
        <p style="color: #f5222d">* 以下属性均为正向(可用)选择 *</p>
        <a-row>
          <a-col :md="12" :sm="24">
            <a-form-item label="品牌">
              <a-tooltip>
                <template slot="title" v-if="coupon.brandList && coupon.brandList.length > 2">
                  {{ getName(coupon.brandList, queryData.brands) }}
                </template>
                <a-select
                  mode="multiple"
                  :maxTagCount="2"
                  autoClearSearchValue
                  show-search
                  allowClear
                  v-decorator="['brandList']"
                  placeholder="请选择"
                  :filter-option="filterOption"
                  @change="e => changeGoodsAttr(e, 'brand')"
                >
                  <a-select-option v-for="(item, index) in queryData.brands" :key="index" :value="item.id">{{ item.attribname }}</a-select-option>
                </a-select>
              </a-tooltip>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="年份">
              <a-select v-decorator="['year']" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
                <a-select-option v-for="(item, index) in queryData.years" :key="index" :value="item.id">{{ item.attribname }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="大类">
              <a-tooltip>
                <template slot="title" v-if="coupon.bigClassList && coupon.bigClassList.length > 3">
                  {{ getName(coupon.bigClassList, queryData.categorys) }}
                </template>
                <a-select
                  mode="multiple"
                  :maxTagCount="3"
                  autoClearSearchValue
                  show-search
                  allowClear
                  v-decorator="['bigClassList']"
                  placeholder="请选择"
                  :filter-option="filterOption"
                  @change="e => changeGoodsAttr(e, 'bigClass')"
                >
                  <a-select-option v-for="(item, index) in queryData.categorys" :key="index" :value="item.id">{{ item.attribname }}</a-select-option>
                </a-select>
              </a-tooltip>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="小类">
              <a-tooltip>
                <template slot="title" v-if="coupon.smallClassList && coupon.smallClassList.length > 3">
                  {{ getName(coupon.smallClassList, queryData.scategorys) }}
                </template>
                <a-select
                  mode="multiple"
                  :maxTagCount="3"
                  autoClearSearchValue
                  show-search
                  allowClear
                  v-decorator="['smallClassList']"
                  placeholder="请选择"
                  :filter-option="filterOption"
                  @change="e => changeGoodsAttr(e, 'smallClass')"
                >
                  <a-select-option v-for="(item, index) in queryData.scategorys" :key="index" :value="item.id">{{ item.attribname }}</a-select-option>
                </a-select>
              </a-tooltip>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="波段">
              <a-tooltip>
                <template slot="title" v-if="coupon.bandList && coupon.bandList.length > 3">
                  {{ getName(coupon.bandList, queryData.bands) }}
                </template>
                <a-select
                  mode="multiple"
                  :maxTagCount="3"
                  autoClearSearchValue
                  show-search
                  allowClear
                  v-decorator="['bandList']"
                  placeholder="请选择波段"
                  :filter-option="filterOption"
                  @change="e => changeGoodsAttr(e, 'band')"
                >
                  <a-select-option v-for="(item, index) in queryData.bands" :key="index" :value="item.id">{{ item.attribname }}</a-select-option>
                </a-select>
              </a-tooltip>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="季节">
              <a-tooltip>
                <template slot="title" v-if="coupon.seasonList && coupon.seasonList.length > 4">
                  {{ getName(coupon.seasonList, queryData.season) }}
                </template>
                <a-select
                  mode="multiple"
                  :maxTagCount="4"
                  autoClearSearchValue
                  show-search
                  allowClear
                  v-decorator="['seasonList']"
                  placeholder="请选择"
                  :filter-option="filterOption"
                  @change="e => changeGoodsAttr(e, 'season')"
                >
                  <a-select-option v-for="(item, index) in queryData.seasons" :key="index" :value="item.id">{{ item.attribname }}</a-select-option>
                </a-select>
              </a-tooltip>
            </a-form-item>
          </a-col>
        </a-row>
      </template>
      <a-divider style="margin-top: 0" />
      <a-form-item label="优惠券说明">
        <a-textarea rows="4" placeholder="请输入" v-decorator="['details']" />
      </a-form-item>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose">取消</a-button>
        <a-button type="primary" htmlType="submit">确定</a-button>
      </div>
    </a-form>
    <j-import-modal ref="importModal" :url="getImportUrl()" :uploadParams="getUploadParams()" @ok="importOk" :templateUrl="templateUrl()" :serviceId="4"></j-import-modal>
  </a-drawer>
</template>
<script>
import pick from 'lodash.pick'
import moment from 'moment'
import 'moment/locale/zh-cn'
import JImportModal from '@/components/qiniuUpload/JImportModal'
import { queryUploadSuccess } from '@/components/qiniuUpload/common'
import globalData from '@/assets/js/common'
import { couponEditDetail } from '@/api/box/setting'

export default {
  props: ['queryData'],
  data() {
    return {
      moment,
      visible: false,
      editId: '',
      coupon: {},
      title: '',
      brandsList: [],
      bandsList: [],
      seasonList: [],
      smallList: [],
      bigList: [],
      form: this.$form.createForm(this),
      toggle: {
        expireType: null,
        goods: false,
        type: null,
        goodsFilter: null
      },
      timer: null
    }
  },
  components: { JImportModal },
  computed: {
    getName(list, data) {
      return (list, data) => {
        if (list && list.length > 0) {
          let result = []
          for (let e of data) {
            list.forEach(key => {
              if (key == e.id) {
                result.push(e)
              }
            })
          }
          let st = result.map(e => e.attribname).join(',')
          return st
        } else {
          return ''
        }
      }
    }
  },
  beforeDestroy() {
    // 页面销毁后同时清除定时器，避免占用内存
    clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    onClose() {
      this.form.resetFields()
      this.visible = false
      this.toggle = {
        expireType: null,
        goods: false,
        type: null,
        goodsFilter: null
      }
    },
    showModal(title, record) {
      this.visible = true
      this.title = title
      this.editId = record == 'add' ? 'add' : record.id
      this.coupon = record == 'add' ? {} : record
      if (record != 'add') {
        this.initialCoupon()
      } else {
        this.toggle = {
          expireType: null,
          goods: false
        }
      }
    },
    initialCoupon() {
      let self = this
      let arr = ['useType', 'brand', 'band', 'bigClass', 'smallClass', 'season']
      this.formatCoupon(arr)

      this.toggle.expireType = this.coupon.expireType
      this.toggle.type = this.coupon.type
      this.toggle.goodsFilter = this.coupon.goodsFilter
      if (this.coupon.goodFtiler != 3) {
        this.toggle.goods = true
      } else {
        this.toggle.goods = false
      }
      console.log(this.coupon)

      this.$nextTick(() => {
        self.form.setFieldsValue(pick(this.coupon, 'name', 'innerName', 'type', 'overly', 'expireType', 'useTypeList', 'goodFtiler', 'details'))
        if (this.toggle.type == 1) {
          self.form.setFieldsValue(pick(this.coupon, 'discount', 'exchangeQuantity'))
        } else if (this.toggle.type == 0) {
          self.form.setFieldsValue(pick(this.coupon, 'amount', 'payDiscount', 'useLimit', 'sameTypeAdd'))
        }

        if (this.toggle.expireType == 0) {
          self.form.setFieldsValue({
            startDate: moment(this.coupon.startDate),
            endDate: moment(this.coupon.endDate)
          })
        } else if (this.toggle.expireType == 1) {
          self.form.setFieldsValue(pick(this.coupon, 'endDays'))
        }

        if (this.toggle.goods) {
          self.form.setFieldsValue(pick(this.coupon, 'goodsFilter', 'brandList', 'year', 'bigClassList', 'smallClassList', 'bandList', 'seasonList'))
        }
      })
    },
    formatCoupon(arr) {
      for (let key of arr) {
        this.coupon[`${key}List`] = this.coupon[key] != null ? this.coupon[key].split(',') : []
        if (this.coupon[`${key}List`].length > 0) {
          let arr = []
          this.coupon[`${key}List`].forEach(el => {
            arr.push(parseInt(el))
          })
          this.coupon[`${key}List`] = arr
        }
      }
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleSelectChange(value, type) {
      console.log(value)
      console.log(type)
      switch (type) {
        case 'type':
          this.toggle.type = value
          break
        case 'expireType':
          this.toggle.expireType = value
          break
        case 'goodFilter':
          this.toggle.goods = value !== 3
          break
        case 'goodsFilter':
          this.toggle.goodsFilter = value
          break
      }
    },
    typeChange(e) {
      this.toggle.type = e.target.value
    },
    changeGoodsAttr(list, type) {
      switch (type) {
        case 'brand':
          this.coupon.brandList = list
          break
        case 'bigClass':
          this.coupon.bigClassList = list
          break
        case 'smallClass':
          this.coupon.smallClassList = list
          break
        case 'band':
          this.coupon.bandList = list
          break
        case 'season':
          this.coupon.seasonList = list
          break
      }
    },
    // 导入
    handleImportXls() {
      this.$refs.importModal.show()
    },
    // 处理上传业务的后台地址
    getImportUrl() {
      return ''
    },
    getUploadParams() {
      // console.log({...globalData.uploadParams})
      return { ...globalData.uploadParams }
    },
    // 上传成功后的方法
    importOk(result, fileList) {
      console.log(result, fileList)
      let that = this
      queryUploadSuccess(this.timer, result, 60000, function(x) {
        console.log(x)
        if (x == 'done' || x == 'warning') {
          that.$refs.importModal.close()
        }
        if (x == 'done') {
          console.log(fileList)
        }
      })
    },
    templateUrl() {
      return 'https://img.bzhz.jnbygroup.com/coupon-goods-sample.xls'
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log(values)
          let formValue = this.filterFields(values)
          this.submitForm(formValue)
        }
      })
    },
    filterFields(values) {
      let formValue = {}
      Object.keys(values).forEach(i => {
        if (values[i] !== '' && values[i] !== undefined) {
          if (i == 'useTypeList' && values[i].length > 0) {
            formValue.useType = values[i].join(',')
          } else if (i == 'brandList' && values[i].length > 0) {
            formValue.brand = values[i].join(',')
            formValue.brandName = this.queryData.brands
              .filter(e => values[i].includes(e.id))
              .map(i => i.attribname)
              .join(',')
          } else if (i == 'bigClassList' && values[i].length > 0) {
            formValue.bigClass = values[i].join(',')
            formValue.bigclassName = this.queryData.categorys
              .filter(e => values[i].includes(e.id))
              .map(i => i.attribname)
              .join(',')
          } else if (i == 'smallClassList' && values[i].length > 0) {
            formValue.smallClass = values[i].join(',')
            formValue.smallclassName = this.queryData.scategorys
              .filter(e => values[i].includes(e.id))
              .map(i => i.attribname)
              .join(',')
          } else if (i == 'bandList' && values[i].length > 0) {
            formValue.band = values[i].join(',')
            formValue.bandName = this.queryData.bands
              .filter(e => values[i].includes(e.id))
              .map(i => i.attribname)
              .join(',')
          } else if (i == 'seasonList' && values[i].length > 0) {
            formValue.season = values[i].join(',')
            formValue.seasonName = this.queryData.seasons
              .filter(e => values[i].includes(e.id))
              .map(i => i.attribname)
              .join(',')
          } else if (i == 'endDate') {
            formValue.endDate = values[i].format('YYYY-MM-DD')
          } else if (i == 'startDate') {
            formValue.startDate = values[i].format('YYYY-MM-DD')
          } else {
            formValue[i] = values[i]
          }
        }
      })
      console.log('formValue', formValue)
      return formValue
    },
    submitForm(values) {
      let param = {
        requestData: values
      }
      if (this.editId != 'add') param.requestData.id = this.editId
      couponEditDetail(param).then(res => {
        if (res.code == 0) {
          this.$message.success('编辑成功！')
          this.onClose()
          this.$emit('editOk')
        } else {
          this.$message.warning(res.msg)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped></style>

